import json
import logging
import os
import time

import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

from config.Configmanage import WebEnvironment

from mongo.mongobase import WebMongo

'''



'''
# 读取配置信息


from random import randint

with open('../webui/webuidata/caselist.json', encoding='gbk') as f:
    config = json.load(f)
    for key, value in config.items():
        pass

    configename = value['配置信息']

resources_dict = WebEnvironment().load_file(f'../config/环境配置.json')

CONFIG = resources_dict[configename].information

WAIT = int(CONFIG[2]['元素显性等待时间'])
url = CONFIG[0]['url']

CHROME_DRIVER_PATH = '../webui/webbase/chromedriver'


class DriverBase:
    def __init__(self, type='chrome'):
        self.type = type

        self.web_driver = None
        self.windows = dict()
        self.recent_type = self.type

    def init_driver(self):
        if self.type == "firefox":
            self._init_firefox()
        elif self.type == "chrome":
            self._init_chrome()
        elif self.type == "random":
            if randint(0, 1) == 0:
                self._init_firefox()
                self.recent_type = "firefox"
            else:
                self._init_chrome()
                self.recent_type = "chrome"
        self.windows['main'] = self.web_driver.window_handles[-1]

    def _init_firefox(self):

        self.web_driver = webdriver.Firefox()

    def _init_chrome(self):

        self.web_driver = webdriver.Chrome(executable_path=CHROME_DRIVER_PATH)

    def nav(self, url):
        if self.web_driver:
            self.web_driver.get(url)

    def maximum(self):
        if self.web_driver:
            self.web_driver.maximize_window()

    @property
    def title(self):
        if self.web_driver:
            return self.web_driver.title

    def close(self):
        if self.web_driver:
            self.web_driver.quit()
            self.web_driver = None
            self.windows.clear()

    def open_new_window(self, name):
        self.web_driver.execute_script(f"window.open('about:blank', '{name}')")
        self.windows[name] = self.web_driver.window_handles[-1]

    def switch_to_window(self, name):
        if name not in self.windows:
            return
        self.web_driver.switch_to.window(self.windows[name])

    def close_window(self, name):
        if name not in self.windows:
            return
        self.web_driver.switch_to.window(self.windows[name])
        self.web_driver.close()


class CaseManage:

    def __init__(self, casepath='../webuidata/webtestcase'):
        self.casepath = casepath  # 汇总的测试用例路径




    # 搜索testcasedata目录下所有测试用例文件汇总 并生成字典
    def merge_json(self):

        case_dict = dict()

        case_list = os.listdir(self.casepath)
        case_len = len(case_list)
        if case_list:

            for case_name in case_list:

                with open(self.casepath + '/' + case_name) as file:
                    json_obj = json.load(file)
                    for key, value in json_obj.items():
                        case_dict[key] = value
                    # config = value['配置信息']
        # print(case_dict)
        return case_dict, case_len

    # 将汇总的测试用例文件保存为json
    def save_json(self):
        case_lise, caselen = self.merge_json()
        # caselist.json
        with open('../webui/webuidata/caselist.json', mode='w+') as file:
            json.dump(case_lise, file, indent=4, ensure_ascii=False)

        return caselen

    # @property
    # def case_config(self):
    #     with oopen('../webui/webuidata/caselist.json') as file:
    #         config_dict=json.load(file)
    #         connfig=config_dict

    # 处理汇总的测试数据，生成每一步的测试数据用于@pytest.mark.parametrize(('caselist'),data)
    @property
    def case_step(self):
        case_step_list = list()
        case_name_list = list()
        # case_step_name_list=list()
        if not os.path.exists('../webui/webuidata/caselist.json'):
            raise WebElementError(f'没有找到文件caselist.json')
        with open('../webui/webuidata/caselist.json', encoding='gbk') as file:
            case_json = json.load(file)
            for key, value in case_json.items():
                _list = value.get('测试步骤', None)
                _list_name = value.get('用例名称', None)
                case_name_list.append(_list_name)

                # print(type(_list))
                for i in range(len(_list)):
                    case_step_list.append(_list[i])

        return case_step_list

    # 新增一个测试用例文件 用于图形界面
    # @classmethod
    # def add_casefile(cls,casedata):
    #
    #     casedata=json.loads(casedata)
    #     casedata = json.loads(casedata)
    #
    #     print(casedata)
    #     caselen=0
    #     for key,value in casedata.items():
    #         caselen+=1
    #     filename=value['页面名称']
    #
    #
    #     # with open(f'../webuidata/{filename}',mode='w+') as afile:
    #     #     json.dump(casedata, afile, indent=4, ensure_ascii=False)
    #
    #     with open(f'../webui/webuidata/webtestcase/{filename}',mode='w+') as afile:
    #         json.dump(casedata, afile, indent=4, ensure_ascii=False)
    #
    #     return caselen

    @property
    def case_step_count(self):
        return len(self.case_step)


def WebElementError(Exception):
    def __init__(self, msg):
        super().__init__(msg)


class PageElementBase:

    def __init__(self, driver, locatoe):
        self.driver = driver

        self.by, self.value, *other = locatoe


    def slip_locatoe(self):
        if self.by == 'xpath':

            self.by = By.XPATH

        elif self.by == 'id':
            self.by = By.ID

        elif self.by == 'css':
            self.by = By.CSS_SELECTOR

        elif self.by == 'class_name':
            self.by = By.CLASS_NAME

        elif self.by == 'link_text':
            self.by = By.LINK_TEXT

        else:
            raise WebElementError(f"系统没有{self.by}定位方法，请使用XPATH，CSS_SELECTOR，ID，CLASS_NAME，LINK_TEXT等方式定位")

    def get_element(self, wait=WAIT):
        self.slip_locatoe()
        try:
            element = WebDriverWait(self.driver, wait).until(lambda x: x.find_element(self.by, self.value))
            return element

        except Exception as e:
            raise e

    def get_elements(self, wait=WAIT):
        self.slip_locatoe()
        try:
            elements = WebDriverWait(self.driver, wait).until(lambda x: x.find_element(self.by, self.value))
            return elements

        except Exception as e:
            raise e

    def input_text(self, text):
        self.get_element().send_keys(text)

    def click(self):
        self.get_element().click()

    def get_input_text(self):
        self.get_element().get_attribute('value')

    @property
    def text(self):
        # self.get_element().text
        return self.get_element().text

    # 元素是否可见
    def is_displayed(self):
        return self.get_element().is_displayed()

    # 元素是否选中
    def is_selected(self):

        return self.get_element().is_selected()

    def double_click(self):
        self.get_element().double_click()


caseui = CaseManage()
data = caseui.case_step
count_case_step = caseui.case_step_count
log_format = "[%(asctime)s][%(name)s]-<thread:%(thread)s>-(line:%(lineno)s), [%(levelname)s]: %(message)s"


# resources_dict = WebEnvironment().load_file('../config/环境配置.json')


@pytest.mark.parametrize(('caselist'), data)
class TestPageBase:
    count = 0

    # now_time = time.strftime(f'%Y-%m-%d-%H-%M-%S')

    def setup_class(self):

        self.now_time = time.strftime(f'%Y-%m-%d:%H:%M:%S')
        self.logtime = time.strftime(f'%Y-%m-%d')
        self.web = DriverBase()
        self.web.init_driver()
        self.web.web_driver.get(url)
        self.logger = logging.getLogger(f'/UI{self.now_time}')
        self.logger.setLevel(logging.INFO)
        self.file_handler = logging.FileHandler(f'../report/UI1{self.logtime}')
        self.logger.addHandler(self.file_handler)

    def teardown_class(self):
        # pass
        # assert 1==1

        self.web.close()

        self.file_handler.setFormatter(logging.Formatter(fmt=log_format))

    def setup(self):

        pass

    def teardown(self):
        TestPageBase.count += 1
        self.logger.info(f'总测试步骤为{count_case_step}，已完成{TestPageBase.count},'
                         f'完成百分比{(TestPageBase.count / count_case_step) * 100}%')

    # @pytest.mark.parametrize(('caselist'), data)
    def test_ui(self, caselist):

        operate, elementname, locatoe = caselist
        loginfo = f"{self.now_time},执行步骤： {operate},{elementname}"
        print(operate, type(operate))
        self.logger.info(loginfo)

        t_list = ["点击", "输入", "断言", "元素是否可见", "元素是否选中", "双击"]

        if operate in t_list:
            element = PageElementBase(self.web.web_driver, locatoe)
            t_dict = {
                "点击": element.click,
                "输入": element.input_text,
                "断言": element.text,
                "元素是否可见": element.is_displayed,
                "元素是否选中": element.is_selected,
                "双击": element.double_click

            }
            if operate == '输入':
                t_dict['输入'](locatoe[2])

            elif operate == '断言':
                assert locatoe[2] in t_dict['断言']



            else:
                t_dict[f'{operate}']()
                print(operate)

            # if operate == '点击':
            #
            #     element.click()
            #
            # elif operate == '输入':
            #     # locatoe=['xpath', '//*[@id="kw"]', '测试']
            #     element.input_text(locatoe[2])
            #
            # # 只先支持断言元素的值
            # elif operate == '断言':
            #
            #     assert locatoe[2] in element.text

            # elif operate=='关闭窗口':
            #     pass

            # elif operate=='右键':
            #     pass
            # elif operate=='切换窗口':
            #     pass
            # elif operate=='鼠标拖拽':
            #     pass


        # elif operate=='关闭浏览器':
        #
        #     self.web.close()

        else:
            raise WebElementError(f'目前系统只支持{t_list}操作')
